import {Component, ElementRef, OnDestroy, OnInit, TemplateRef} from "@angular/core";
import {NzMessageService} from "ng-zorro-antd";
import {FetchService} from "../../../../core/net/fetch.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {isToday, format} from 'date-fns';
import {Topology, Rect} from 'topology-core';
import * as _ from 'lodash';
import {Options} from 'topology-core/options';
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";
import {Router} from "@angular/router";
import {Node} from 'topology-core/models/node';
import {Pen} from 'topology-core/models/pen';
import {NzModalRef, NzModalService} from "ng-zorro-antd/modal";

@Component({
  selector: 'app-emergency-yjq',
  templateUrl: './emergency-yjq.component.html',
  styleUrls: ['../emergency-dispatch-common.scss', './emergency-yjq.component.scss']
})

export class EmergencyYjqComponent implements OnInit, OnDestroy {
  manageId = JSON.parse(localStorage.userInfo).manageId;
  selectedValue = '1';
  canvas: Topology;
  canvasOptions: Options = {};
  rect: Rect;
  hoverItem = {
    top: '0px',
    left: '0px',
    name: '-',
    zh: '-',
    dq: '-',
  };
  infoShow = false;
  glcData;
  pptnrList = [];
  pens: any;

  // 文件预览
  tplModal: NzModalRef;
  fileSrc = '';
  fileId = '';

  // gate		闸门
  // gate_out 	退水闸
  // pump		泵站
  // ZZ			水位站
  // ZQ			水文站
  // text_h		水位
  // text_q		流量
  ghtData = [{"id": "YJ-DC01", "name": "大口子沟渡槽", "zh": "18+246", "dq": "22.3"},
    {"id": "YJ-DC02", "name": "大佛寺渡槽", "zh": "22+971", "dq": "126.0"},
    {"id": "YJ-DC03", "name": "石空沟渡槽", "zh": "26+200", "dq": "45.8"},
    {"id": "YJ-DC04", "name": "罗家沟渡槽", "zh": "29+870", "dq": "157.0"},
    {"id": "YJ-DC05", "name": "张义沟渡槽", "zh": "34+215", "dq": "93.0"},
    {"id": "YJ-DC06", "name": "新寺沟渡槽", "zh": "38+630", "dq": "75.0"},
    {"id": "YJ-DC07", "name": "枣园沟渡槽", "zh": "44+218", "dq": "77.0"},
    {"id": "YJ-DC08", "name": "高山寺输水渡槽", "zh": "46+617", "dq": "13.0"},
    {"id": "YJ-DC09", "name": "太阳梁渡槽", "zh": "53+236", "dq": "70.0"},
    {"id": "YJ-DC10", "name": "红崖沟输水渡槽", "zh": "62+776", "dq": "463.0"},
    {"id": "YJ-DC11", "name": "风塘沟输水渡槽", "zh": "70+356", "dq": "132.0"},
    {"id": "YJ-TSZ01", "name": "大口子退水闸", "zh": "18+246", "dq": "20.0"},
    {"id": "YJ-TSZ02", "name": "余丁退水闸", "zh": "20+411", "dq": "60.0"},
    {"id": "YJ-TSZ03", "name": "石空退水闸", "zh": "26+200", "dq": "30.0"},
    {"id": "YJ-TSZ04", "name": "太平退水闸", "zh": "31+823", "dq": "45.0"},
    {"id": "YJ-TSZ05", "name": "新寺沟退水闸", "zh": "34+215", "dq": "15.0"},
    {"id": "YJ-TSZ06", "name": "枣园退水闸", "zh": "43+659", "dq": "15.0"},
    {"id": "YJ-TSZ07", "name": "沙坑退水闸", "zh": "59+330", "dq": "12.0"},
    {"id": "YJ-TSZ08", "name": "红崖退水闸", "zh": "61+582", "dq": "12.0"},
    {"id": "YJ-TSZ09", "name": "三塘墩退水闸", "zh": "67+987", "dq": "9.0"},
    {"id": "YJ-TSZ10", "name": "狼布井退水闸", "zh": "", "dq": "9.0"},
    {"id": "YJ-TSZ11", "name": "碱沟退水闸", "zh": "79+629", "dq": "15.0"},
    {"id": "YJ-HD01", "name": "狼八井涵洞", "zh": "31+105", "dq": "55.4"},
    {"id": "YJ-HD02", "name": "头道冒涵洞", "zh": "33+980", "dq": "5.0"},
    {"id": "YJ-HD03", "name": "三道冒涵洞", "zh": "41+344", "dq": "22.0"},
    {"id": "YJ-HD04", "name": "蚂蟥沟涵洞", "zh": "48+247", "dq": "18.0"},
    {"id": "YJ-HD05", "name": "付家坟涵洞", "zh": "72+336", "dq": "9.0"},
    {"id": "YJ-HD06", "name": "二道梁子涵洞", "zh": "73+328", "dq": "15.0"},
    {"id": "YJ-HD07", "name": "狼布井涵洞", "zh": "76+350", "dq": "64.0"},
    {"id": "YJ-HD08", "name": "小碱沟涵洞", "zh": "78+914", "dq": "6.5"},
    {"id": "YJ-YLY01", "name": "五趟沟溢流堰", "zh": "49+560", "dq": "3.0"},
    {"id": "YJ-YLY02", "name": "破石沟溢流堰", "zh": "56+514", "dq": "46.0"},
    {"id": "YJ-YLY03", "name": "三塘墩溢流堰", "zh": "67+987", "dq": "2.0"}];

  drpTotal = '-';
  flow = '-';
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private fetchService: FetchService,
    private el: ElementRef,
    private router: Router,
    private modal: NzModalService,
    private sanitizer: DomSanitizer
  ) {
    if (this.manageId == '10001') {
      this.selectedValue = '2';
    } else {
      this.selectedValue = this.manageId;
    }
  }

  ngOnInit(): void {
    window.addEventListener('resize', this.debounce(() => {
      this.onResize();
    }, 500));
    this.getPptnrData();
    this.getMapData();
  }

  ngOnDestroy(): void {
    this.canvas.destroy();
  }

  // 防抖函数
  debounce(func, wait?, immediate?): any {
    let timeout;
    return () => {
      const context = this;
      const args = arguments;
      const later = () => {
        timeout = null;
        if (!immediate) {
          func.apply(context, args);
        }
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  }

  // 窗口变化
  onResize() {
    console.log('windonw is resize');
    const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
    const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
    this.rect = this.canvas.getRect();
    if (this.rect.width / this.rect.height > w / h) {
      this.canvas.scale(w / this.rect.width * 0.98);
    } else {
      this.canvas.scale(h / this.rect.height * 0.95);
    }
    this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
  }

  getMapData(): void {
    this.fetchService.get<any>('assets/data/shdd/1.json').subscribe(res => {
      sessionStorage.setItem('yjqRes', JSON.stringify(res));
      if (this.canvas) {
        // 重置画布数据
        this.canvas.open({
          id: '',
          version: '',
          name: 'new空白文件',
          desc: '',
          image: '',
          userId: '',
          class: '',
          component: false,
          shared: false
        });
      } else {
        // 创建画布
        this.canvasOptions.on = this.onMouseEvent.bind(this);
        this.canvas = new Topology('topology-canvas', this.canvasOptions);
      }
      this.canvas.open(res);
      this.pens = this.canvas.data.pens;
      // 设置画布
      this.onResize();
    });

  }

  // 概化图元素事件
  onMouseEvent(event: string, node: any) {
    if (event === 'moveInNode') {
      if (node.data != '' && (['ducao', 'zhamen', 'handong', 'yiliuyan'].indexOf(node.data.type) > -1)) {
        this.infoShow = true;
        const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
        const featureH = _.max(yArr) - _.min(yArr);
        this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 7) + 'px';
        this.hoverItem.left = (node.rect.center.x - 76) + 'px';
        const nodeId = node.data.id;
        this.ghtData.map(item => {
          if (item.id == nodeId) {
            this.hoverItem.dq = item.dq || '-';
            this.hoverItem.zh = item.zh || '-';
            this.hoverItem.name = item.name || '-';
          }
        });
      }
    }
    if (event === 'moveOutNode') {
      this.infoShow = false;
    }
    if (event === 'node') {
      if (node.data.clickable) {
         this.reDraw(node);
       /* console.log(this.canvas);
        const pens = {...{}, ...this.pens};
        for (const key of Object.keys(pens)) {
          if (pens[key].id == node.id) {
            pens[key].strokeStyle = '#ff1343';
            pens[key].lineWidth = 6;
          }
        }
        this.canvas.redo();
        this.canvas.updateProps(true, pens);*/
        // this.nodeAnimate(node);
      }
    }
  }

  nodeAnimate(node): void {
    // 复制当前节点状态
    const state = Node.cloneState(node);
    // 1. 自定义动画代码
    /*
    state.rect.y -= 100;
    state.rect.ey -= 100;
    node.animateFrames.push({
      duration: 1000,
      linear: true,
      state
    });

    // 回到初始状态
    const state2 = Node.cloneState(node);
    node.animateFrames.push({
      duration: 1000,
      linear: true,
      state: state2
    });
    */

    // 2. 心跳动画代码
    state.rect.x -= 5;
    state.rect.ex += 5;
    state.rect.y -= 5;
    state.rect.ey += 5;
    state.rect.width += 5;
    state.rect.height += 10;
    node.animateFrames.push({
      duration: 100,
      linear: true,
      state
    });
    node.animateFrames.push({
      duration: 400,
      linear: true,
      state: Node.cloneState(node)
    });
    // 心跳动画end

    node.animateDuration = 0;
    for (const item of node.animateFrames) {
      node.animateDuration += item.duration;
    }

    // 2.A 设置开始播放属性（为当前时间）
    node.animateStart = Date.now();

    // 3. 通知画布刷新动画绘画
    this.canvas.animate();
  }

  getPptnrData(): void {
    this.fetchService.post<any>('intake/wrsPptnR/ddList', {description: 2}).subscribe(res => {
      this.pptnrList = res.data;
    });
  }

  goBack(): void {
    this.router.navigate([`/realtime-control/emergency-home`]);
  }

  reDraw(node): void {
    const pensJson = JSON.parse(sessionStorage.getItem('yjqRes'));
    pensJson.pens.map(pen => {
      if ((pen.data.pid && (pen.data.pid).indexOf(node.data.id) > -1) || (pen.data.id == node.data.id)) {
        if (pen.data.type) {
          // 修改图片
          pen.image = '/yjq_web/assets/images/ght/newicons/' + pen.data.type + '2.png';
        } else {
          // 修改线颜色
          pen.strokeStyle = '#ff1343';
          pen.lineWidth = 6;
        }

      }

    });
    this.canvas.open({
      id: '',
      version: '',
      name: 'new空白文件' + new Date().getTime(),
      desc: '',
      image: '',
      userId: '',
      class: '',
      component: false,
      shared: false
    });
    this.canvas.open(pensJson);
    // 设置画布
    this.onResize();
  }

  viewFile(tplContent: TemplateRef<{}>): void {
    const that = this;
    this.fileSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/2c6ed40f5a88459f938315061f4c28a5`;

    this.tplModal = this.modal.create({
      nzTitle: '文件预览',
      nzContent: tplContent,
      nzWidth: 1100,
      nzStyle: {top: '20px'},
      nzClassName: 'custom-modal',
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: true,
      nzOnCancel(): void {
        that.destroyModal();
      }
    });
  }

  destroyModal() {
    this.tplModal.destroy();
  }

}
